<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 电信年度收入
 *
 * @icon fa fa-circle-o
 */
class Dxcaiwushow extends Backend
{

    /**
     * Dxcaiwushow模型对象
     * @var \app\admin\model\Dxcaiwushow
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Dxcaiwushow;
        $this->view->assign("ctypeList", $this->model->getCtypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        $input = input('param.');
        $filter = isset($input['filter'])?json_decode($input['filter'],true):'';
        if(empty($filter['year'])){
            $year = date('Y')-1;
            $year = 2023;
        }else{
            $year = $filter['year'];
        }

        $list = $this->model
            ->where("")
            ->order('id asc')
            ->where('id <= 23')
            ->paginate(30);
        //print_r($list->toArray());die();
        foreach($list as $row){

           if($row['shouru'] == '电信佣金'){
               $row->yue1 = dxyj_find(1,$year);
               $row->yue2 = dxyj_find(2,$year);
               $row->yue3 = dxyj_find(3,$year);
               $row->yue4 = dxyj_find(4,$year);
               $row->yue5 = dxyj_find(5,$year);
               $row->yue6 = dxyj_find(6,$year);
               $row->yue7 = dxyj_find(7,$year);
               $row->yue8 = dxyj_find(8,$year);
               $row->yue9 = dxyj_find(9,$year);
               $row->yue10 = dxyj_find(10,$year);
               $row->yue11 = dxyj_find(11,$year);
               $row->yue12 = dxyj_find(12,$year);
           }
           //echo $row['shouru'];
           if($row['shouru'] == '电信社区佣金'){
                $row->yue1 =  dxyj_find(1,$year,'sqyj');
                $row->yue2 = dxyj_find(2,$year,'sqyj');
                $row->yue3 = dxyj_find(3,$year,'sqyj');
                $row->yue4 = dxyj_find(4,$year,'sqyj');
                $row->yue5 = dxyj_find(5,$year,'sqyj');
                $row->yue6 = dxyj_find(6,$year,'sqyj');
                $row->yue7 = dxyj_find(7,$year,'sqyj');
                $row->yue8 = dxyj_find(8,$year,'sqyj');
                $row->yue9 = dxyj_find(9,$year,'sqyj');
                $row->yue10 = dxyj_find(10,$year,'sqyj');
                $row->yue11 = dxyj_find(11,$year,'sqyj');
                $row->yue12 = dxyj_find(12,$year,'sqyj');
            }
            if($row['shouru'] == '佣金合计：'){
                $rang = range(1,12);
              foreach ($rang as $v){
                  $yue = 'yue'.$v;
                  $row->$yue = num_sum($list[0][$yue],$list[1][$yue]);
              }
            }
            if($row['shouru'] == '室内调测费'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'sntc');
                }
            }
            if($row['shouru'] == '续费'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'xufe');
                }
            }
            if($row['shouru'] == '安装费'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'azf');
                }
            }
            if($row['shouru'] == '其他' && $row['ctype'] == 1){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'ru_other');
                }
            }
            if($row['shouru'] == '合计收入：'){
                $rang = range(1,12);
                foreach ($rang as $v) {
                    $yue = 'yue' . $v;
                    $arr = [$list[3][$yue], $list[4][$yue], $list[5][$yue], $list[6][$yue]];
                    $sum = array_sum($arr);
                    $row->$yue = $sum==0?'':float_two($sum)+0;
                }
            }
            if($row['shouru'] == '房租'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'fangzu');
                }
            }
            if($row['shouru'] == '免费线'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'mfx');
                }
            }
            if($row['shouru'] == '其他' && $row['ctype'] == 2){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'zhi_other');
                }
            }
            if($row['shouru'] == '预存续费'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'yucun');
                }
            }
            if($row['shouru'] == '电信快捷宽带'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'kjkd');
                }
            }
            if($row['shouru'] == '网兆税费'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'wzsf');
                }
            }
            if($row['shouru'] == '工资（对公户支付）'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'gz');
                }
            }
            if($row['shouru'] == '对公户杂费'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'dgh');
                }
            }
            if($row['shouru'] == '社保费'){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'sbf');
                }
            }
            //print_r($row);die();
            if($row['shouru'] == '合计支出：'){
                $rang = range(1,12);
                foreach ($rang as $v) {
                    $yue = 'yue' . $v;
                    $arr = [
                        $list[9][$yue], $list[10][$yue], $list[11][$yue], $list[12][$yue],
                        $list[13][$yue], $list[14][$yue], $list[15][$yue], $list[16][$yue],$list[17][$yue],
                    ];
                    $sum = array_sum($arr);
                    $row->$yue = $sum==0?'':float_two($sum)+0;
                }
            }
            //$row['shouru'] == '对公户其他收入：'
            if(strpos($row['shouru'],'对公户其他收入') !== false){
                $rang = range(1,12);
                foreach ($rang as $v){
                    $yue = 'yue'.$v;
                    $row->$yue = dxyj_find($v,$year,'dg_shouru');
                }
            }
            if(strpos($row['shouru'],'利润') !== false){
                $rang = range(1,12);
                foreach ($rang as $v) {
                    $yue = 'yue' . $v;
                    $n =(float)$list[2][$yue] + (float)$list[7][$yue]-(float)$list[18][$yue]+(float)$list[19][$yue];
                    $row->$yue = $n?float_two($n):'';
                }
            }

            $row->year = $year;
            $heji = array_sum([
                $row->yue1,$row->yue2,$row->yue3,$row->yue4,$row->yue5,$row->yue6,
                $row->yue7,$row->yue8,$row->yue9,$row->yue10,$row->yue11,$row->yue12]);
            $row->heji = float_two($heji);

        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index2()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list =Db::table('fa_dxcaiwushow2')
            ->where('isshow="1"')
            ->where($where)

            ->order('id desc')
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    public function yearlist(){
        $list = range(2023,2028);
        $list2 = [];
        foreach($list as $k=>$v) {
            $list2[$k]['id'] = $v;
            $list2[$k]['name'] = $v;
            $list2[$k]['pid'] = 0;
        }
        $total = count($list2);
        return json(['list' => $list2, 'total' => $total]);
    }

    public function monthlist(){
        $list = range(1,12);
        $list2 = [];
        foreach($list as $k=>$v) {
            $list2[$k]['id'] = $v;
            $list2[$k]['name'] = $v;
            $list2[$k]['pid'] = 0;
        }
        $total = count($list2);
        return json(['list' => $list2, 'total' => $total]);
    }

    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = Db::table('fa_dxcaiwushow2')
            ->where('isshow="1"')->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                Db::table('fa_dxcaiwushow2')
                    ->where('isshow="1"')->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                Db::table('fa_dxcaiwushow2')
                    ->where('isshow="1"')->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist =   Db::table('fa_dxcaiwushow2')
                ->where('isshow="1"')->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => $item[$primarykey] ?? '',
                        $field      => $item[$field] ?? '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        //var_export($list);
        return json(['list' => $list, 'total' => $total]);
    }


}
